package com.jiawei.permission;

import com.alibaba.fastjson.JSONArray;
import com.jiawei.entity.database.User;
import com.jiawei.mapper.PremMapper;
import com.jiawei.util.JwtUtil;
import com.jiawei.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author : willian fu
 * @version : 1.0
 * 检查权限范围是否需要拦截
 */
@Component
public class PermissionCheck {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private PremMapper premMapper;

    @Autowired
    private JwtUtil jwtUtil;

    @Value("${customize.token}")
    private String header;

    @Value("${customize.expires}")
    private String expires;

    /**
     * @param perm    请求的权限
     * @return 是否有权限
     */
    public boolean verify(String perm) {
        //从token取用户对应的userId
        User user = jwtUtil.jwtGetUser();
        if (user != null) {
            //先从redis取用户权限，如果没有再从数据库取
            String permission = redisTemplate.opsForValue().get("perm:" + user.getId());
            if (StringUtils.isEmpty(permission)){
                List<String> perms = premMapper.getPermByUser(user.getId());
                redisTemplate.opsForValue().set("perm:" + user.getId(), JSONArray.toJSONString(perms),8, TimeUnit.HOURS);
                return perms.contains(perm);
            }else {
                //拥有权限，放行
                return permission.contains(perm);
            }
        }
        return false;
    }
}
